//
//  GTStatusCollectionView.swift
//  swiftWEIbo
//
//  Created by mac－gt on 15/11/28.
//  Copyright © 2015年 mac－gt. All rights reserved.
//

import UIKit

import SDWebImage
class GTStatusCollectionView: UICollectionView,UICollectionViewDataSource,UICollectionViewDelegate{
       let waterLayout=UICollectionViewFlowLayout()
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: waterLayout)
        registerClass(GTStatusCollectionCell.self, forCellWithReuseIdentifier: "cell")
        dataSource=self
        delegate=self
        backgroundColor=UIColor.clearColor()
    }
   
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var status:GTStatus?{
        didSet{
            calcViewSize()
            reloadData()
        }
    }
    func calcViewSize()->CGSize{
        let itemSize=CGSize(width: 90, height: 90)
        waterLayout.itemSize=itemSize
        waterLayout.minimumInteritemSpacing=10
        waterLayout.minimumLineSpacing=10
        let margin=10
        let column=3
        let counts=status?.picURLs?.count ?? 0
        if counts==0{
            return CGSizeZero
        }
        if counts==1{
            let urlString=status?.picURLs?[0].absoluteString
              var size=CGSize(width: 150, height: 120)
            if let image =  SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlString){
                size=image.size
            }
            if size.width<40{
                size.width=40
            }
            waterLayout.itemSize=size
            return size
        }
        if counts==4{
            let width=2 * itemSize.width + CGFloat(margin)
            return CGSize(width: width, height: width)
        }
         let row=(counts + column-1)/column
        let width=CGFloat(column) * itemSize.width + CGFloat(column-1) * CGFloat(margin)
        let height=CGFloat(row) * itemSize.height + CGFloat(row-1) * CGFloat(margin)
        return CGSize(width:width , height: height)
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.status?.picURLs?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell=collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! GTStatusCollectionCell
//        let urlString=status?.pic_urls?[indexPath.item]["thumbnail_pic"] as! String
        //        cell.imageURL=NSURL(string: urlString)
        let url=status?.picURLs?[indexPath.item]
        cell.imageUrl=url
        return cell
    }
}
